/**
 * Created by user on 2015/3/23.
 */

$(document).ready(function () {

    var $box = $('#box_pan');
    var $qabox = $('#qa_box');
    var $rstbox = $('#rstbox');

    $('input:checkbox[name="option"]').click(function (e) {
        var problemIndex = $(this).data('problem-index');
        var optionSize = $(this).data('option-size');

        for (var i = 0; i <= optionSize; i++) {
            $("#" + problemIndex + "b_" + i + "_a").attr('checked', false);
        }
        $("#no" + problemIndex).addClass("ok");
        $(this).attr('checked', true);
    });


    $('#submit_btn').click(function (e) {
        var $this = $(this);
        if ($this.data('redirect')) {
            window.location.href = ctx + $this.data('redirect');
            return;
        }
        if ($box.hasClass('fxpg_result')) {

            $('.ok').removeClass('ok');
            $('input:checkbox[name="option"]').attr('checked', false);

            $box.removeClass('fxpg_result').addClass('fxpg_list');
            $qabox.show();
            $rstbox.hide();

            return;
        }

        var size = $this.data('size');
        var redirect = $(this).data('redirect-serv');
        var spCodesTemp = "";

        $('input:checkbox[name=option]:checked').each(function (i) {
            if (0 == i) {
                spCodesTemp = $.trim($(this).val());
            } else {
                spCodesTemp += ("," + $.trim($(this).val()));
            }
        });

        var words = spCodesTemp.split(',');

        if (spCodesTemp.length > 0 ) {
            if (words.length < size) {
                layer.alert('您还有' + (size - words.length) + '题未答', 2, !1);
            } else if (words.length == size) {
                var formData = {answer: spCodesTemp};
                $.ajax({
                    url: ctx + "/member/questionnaire/answer",
                    data:formData,
                    type: 'POST',
                    success:function(data){
                        if(data.status=='OK'){

                            var rst = data.data;
                            $box.removeClass('fxpg_list').addClass('fxpg_result');
                            $rstbox.html(rst);
                            $qabox.hide();
                            $rstbox.show();

                            if (redirect) {
                                $this.data('redirect', redirect);
                                $this.text('确定');
                            } else {
                                $this.text('重新评测');
                            }
                        }else{
                            layer.alert(data.message, 2, !1);
                        }
                    }
                });
            } else if (words.length > size) {
                layer.alert('数据错误，请刷新页面！', 2, !1);
            }
        }else{
            layer.alert('你还没有进行任何选择！', 2, !1);
        }
    })
});